<template>
	<view class="layout-classify-page">
		<uv-navbar bgColor="#fff" :height="`${menuButtonHeight}px`">
			<template #left>
				<view class="search-box">
					<image @click="hanlderBack" class="back" :src="handleStaticResources('/static/images/back.png')">
					</image>
                    <view class="page-title">
                        {{state.pageTitle}}
                    </view>
					<uv-input shape="circle" placeholder="请输入关键词"
						prefixIcon="search" v-model="state.searchKey"
						:customStyle="{ 'background-color': '#fff','padding':'3px 9px','width':state.searchInputW}" 
                        @confirm="handleSearch"
						prefixIconStyle="font-size: 22px;color: #909399">
						<template #suffix>
							<view class="search-tit" @click="handleSearch">搜索</view>
						</template>
					</uv-input>
				</view>
			</template>
		</uv-navbar>

		<view class="content-box" :style="{ 'padding-top': `${statusBarHeight}px` }">
			<!-- 筛选 -->
			<view class="sift-box" :style="{ 'top': `${statusBarHeight}px` }">
				<view class="item-box" v-for="item, index in state.siftList" :key="index"
					@click="handleSelectSift(index)">
					<view :class="['tit', { 'active': state.selectIndex == index }]">{{ item.label }}</view>
					<uv-icon :name="state.selectIndex == index ? 'arrow-up-fill' : 'arrow-down-fill'" size="10"
						:color="state.selectIndex == index ? '#D33123' : '#D8D8D8'"></uv-icon>
				</view>
			</view>
			<!-- 数据源 -->
			<view v-if="state.goodsList[0].length > 0">
				<view class="goodlist">
					<view v-for="cell, cellIndex in state.goodsList" :key="cellIndex" class="waterfall-box">
						<view v-for="item, index in cell" :key="index" class="card-box">
							<coreshop-goods-card type="vertical" imgHeight="315rpx" imgWidth="315rpx"
								:goodsData="hanldeCombinationGoodsData(item)" @hanldeClickGoods="hanldeClickGoods">
								<template #goodPrice>
									<view class="price-msg" @click="hanldeClickGoods(item)">
										<view class="price-box">
											<view class="price">
												<text class="symbol">￥</text>
												<text class="num">{{ item.price }}</text>
												<text class="mktprice" v-if="item.mktprice">￥{{ item.mktprice }}</text>
											</view>
											<view class="buyCount">已售{{ item.buyCount }}{{ item.unit }}</view>
										</view>
										<Point :data="item" :flex="false" @hanldeClickGoods="hanldeClickGoods(item)">
										</Point>
									</view>
								</template>
							</coreshop-goods-card>
						</view>
					</view>
				</view>
				<view class="no-data" v-if="state.page === state.totalPages">没有更多了</view>
			</view>
			<view v-else class="layout-empty-box">
				<coreshop-empty :mode="EmptyEnum.data" text="暂无商品"></coreshop-empty>
			</view>
		</view>

		<!-- 筛选弹框 -->
		<view class="mask-box" v-if="state.selectIndex != -1" :style="{ 'top': `${statusBarHeight + 40}px` }">
			<view class="mask-bg" @click.stop="handleCloseMask"></view>
			<view class="mask-content" v-if="state.selectIndex == 0">
				<view class="content" v-for="item, index in state.comprehensiveData" :key="index"
					@click="handleSelectSort('sortVal', item.value)">
					<view :class="['tit', { 'active': state.sortVal == item.value }]">{{ item.label }}</view>
					<uv-icon v-if="state.sortVal == item.value" name="checkbox-mark" size="20"
						color="#D33123"></uv-icon>
				</view>
			</view>
			<view class="mask-content" v-if="state.selectIndex == 1">
				<view class="content" v-for="item, index in state.salesVolumeData" :key="index"
					@click="handleSelectSort('priceVal', item.value)">
					<view :class="['tit', { 'active': state.priceVal == item.value }]">{{ item.label }}</view>
					<uv-icon v-if="state.priceVal == item.value" name="checkbox-mark" size="20"
						color="#D33123"></uv-icon>
				</view>
			</view>
			<view class="mask-content" v-if="state.selectIndex == 2">
				<view class="content" v-for="item, index in state.priceSortData" :key="index"
					@click="handleSelectSort('buyCountVal', item.value)">
					<view :class="['tit', { 'active': state.buyCountVal == item.value }]">{{ item.label }}</view>
					<uv-icon v-if="state.buyCountVal == item.value" name="checkbox-mark" size="20"
						color="#D33123"></uv-icon>
				</view>
			</view>
			<view class="mask-content" v-if="state.selectIndex == 3">
				<view class="price">
					<view class="tit">价格区间</view>
					<view class="range">
						<uv-input type="number" v-model="state.priceFrom"
							:customStyle="{ 'width': '100rpx', 'height': '40rpx', 'background-color': '#f1f1f1' }"
							border="surround"></uv-input>
						<view class="line"></view>
						<uv-input type="number" v-model="state.priceTo"
							:customStyle="{ 'width': '100rpx', 'height': '40rpx', 'background-color': '#f1f1f1' }"
							border="surround"></uv-input>
					</view>
				</view>
				<view class="brand" v-if="state.brands.length > 0">
					<view class="tit">品牌</view>
					<view class="brand-box">
						<template v-for="item, index in state.brands" :key="index">
							<view :class="['item', { 'active': item.id == state.brandId }]"
								@click="handleSelectbrand(item.id)" v-if="item.isShow">{{ item.name }}</view>
						</template>
					</view>
				</view>
				<view class="btn">
					<view class="cancel" @click="handleCancelSelect">取消</view>
					<view class="ok" @click="handleOkSelect">确定</view>
				</view>
			</view>
		</view>
		<uv-loading-page :loading="loading" loading-text="加载中..." color="#d33123" loadingColor="#d33123" font-size="24rpx"
			bgColor="rgba(255, 255, 255, 0.2)"></uv-loading-page>
	</view>
</template>
<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useLoadingFn, useSystemInfo } from '@/core/hooks';
	import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
	import { handleStaticResources, handleShowToast, splitArrayByStep } from '@/core/utils';
	import type { Response, GoodsType, GoodsListType } from '@/core/models';
	import { queryGoodsPageList } from '@/core/api';
	import { EmptyEnum } from '@/core/enum';
	import Point from '@/pages/components/custom-page/components/home-goods/point.vue';

	interface QueryParams {
		id ?: string | number;
		key ?: string;
		type ?: string | number;
		catId ?: string | number;
		brandId ?: string | number;
		hot ?: string | number;
		recommend ?: string | number;
		labelId ?: string | number;
	}

	interface SelectVal {
		label ?: string,
		value ?: string,
	}

	// 获取自定义导航栏高度
	const { statusBarHeight, menuButtonHeight } = useSystemInfo();
	const loading = ref(true);
	const state = reactive<{
		searchKey : string;
		page : number;
		totalPages : number;
		goodsList : Array<Array<GoodsListType>>;
		where : any;
		siftList : Array<SelectVal>;
		selectIndex : number;
		comprehensiveData : Array<SelectVal>;
		salesVolumeData : Array<SelectVal>;
		priceSortData : Array<SelectVal>;
		sortVal : string;
		priceVal : string;
		buyCountVal : string;
		brands : Array<any>;
		priceFrom : number | string;
		priceTo : number | string;
		brandId : string;
		pageTitle : string;
        searchInputW:string;
	}>({
		searchKey: "",
		page: 1,
		totalPages: 1,
		goodsList: [[], []],
		where: {},
		siftList: [
			{
				label: '综合',
			}, {
				label: '价格',
			}, {
				label: '销量',
			}, {
				label: '其它',
			}
		],
		selectIndex: -1,
		comprehensiveData: [{
			label: '顺序',
			value: 'asc',
		},
		{
			label: '倒序',
			value: 'desc',
		}],
		salesVolumeData: [{
			label: '从小到大',
			value: 'asc',
		},
		{
			label: '从大到小',
			value: 'desc',
		}],
		priceSortData: [{
			label: '从小到大',
			value: 'asc',
		},
		{
			label: '从大到小',
			value: 'desc',
		}],
		sortVal: "asc",
		priceVal: "",
		buyCountVal: "",
		brands: [],
		priceFrom: '',
		priceTo: '',
		brandId: "",
		pageTitle: "",
        searchInputW:"320rpx"
	})

	let queryParams : QueryParams

	const handleuQueryProduct = useLoadingFn(handleQueryData, loading);

	onReachBottom(() => {
		if (state.totalPages > state.page) {
			state.page++;
			getGoodsPageList();
		}
	});


	onLoad((query : QueryParams) => {
		queryParams = query;
		/** 处理 query 然后获取商品列表  */
		handleuQueryProduct(query);
        
        // #ifdef APP
        state.searchInputW = 'auto';
        // #endif
	});

	onPullDownRefresh(async () => {
		state.page = 1;
		state.totalPages = 1;
        state.goodsList = [[], []];
		await handleuQueryProduct(queryParams);
		uni.stopPullDownRefresh();
	});

	/** 处理 options   */
	async function handleQueryData(options : QueryParams) {
		let where : any = {};
		if (options?.id) {
			where.catId = options?.id;
		}
		if (options?.key) {
			where = { searchName: options.key };
			state.searchKey = options.key;
		}
		if (options.type) {
			if (options.type == 'hot') {
				where = { hot: true };
			}
			if (options.type == 'recommend') {
				where = { recommend: true };
			}
		}
		if (options?.catId) {
			where.catId = options.catId;
		}
		if (options?.brandId) {
			where.brandId = options.brandId;
		}
		if (options?.hot) {
			where.hot = options.hot;
		}
		if (options?.recommend) {
			where.recommend = options.recommend;
		}
		if (options?.labelId) {
			where.labelId = options.labelId;
		}
		state.where = where;
		await getGoodsPageList();
	}

	/** 获取商品列表数据 */
	const getGoodsPageList = async () => {
		let order : Array<string> = [];
		if (state.sortVal) {
			order.push(`sort ${state.sortVal}`)
		}
		if (state.priceVal) {
			order.push(`price ${state.priceVal}`)
		}
		if (state.buyCountVal) {
			order.push(`buyCount ${state.buyCountVal}`)
		}

		let where = {
			...state.where,
			searchName: state.searchKey,
		}
		if (state.priceFrom && state.priceTo) {
			where['priceFrom'] = state.priceFrom;
			where['priceTo'] = state.priceTo;
		}
		if (state.brandId) {
			where['brandId'] = state.brandId;
		}
		const goodsPageList : Response<GoodsListType> = await queryGoodsPageList({
			page: state.page,
			limit: 10,
			order: order.join(','),
			where: JSON.stringify(where)
		});
		state.pageTitle = goodsPageList?.data?.className;
		state.brands = goodsPageList?.data?.brands || [];
		state.totalPages = goodsPageList.data.totalPages;
		let list = splitArrayByStep(goodsPageList.data.list, 2);
		state.goodsList[0] = state.goodsList[0].concat(list[0]);
		state.goodsList[1] = state.goodsList[1].concat(list[1]);
	}

	/** 点击筛选 */
	const handleSelectSift = (index : number) => {
		if (index == state.selectIndex) {
			state.selectIndex = -1;
		} else {
			state.selectIndex = index;
		}
	}

	/** 排序选择 */
	const handleSelectSort = (key : string, val : string) => {
		if (state[key] != val) {
			state[key] = val;
		} else {
			state[key] = '';
		}
		state.page = 1;
		state.goodsList = [[], []];
		state.selectIndex = -1;
		getGoodsPageList();
	}

	/** 品牌选择 */
	const handleSelectbrand = (id : number) => {
		if (state.brandId != String(id)) {
			state.brandId = String(id);
		} else {
			state.brandId = '';
		}
	}

	/** 取消选择 */
	const handleCancelSelect = () => {
		state.priceFrom = '';
		state.priceTo = '';
		state.brandId = '';

		state.page = 1;
		state.goodsList = [[], []];
		state.selectIndex = -1;
		getGoodsPageList();
	}

	/** 确定选择 */
	const handleOkSelect = () => {
		if (state.priceFrom && state.priceTo && Number(state.priceFrom) >= Number(state.priceTo)) {
			handleShowToast('价格区间有误'); return;
		}
		state.page = 1;
		state.goodsList = [[], []];
		state.selectIndex = -1;
		getGoodsPageList();
	}

	/** 搜索 */
	const handleSearch = () => {
		state.page = 1;
		state.sortVal = "asc";
		state.priceVal = "";
		state.buyCountVal = "";
		state.priceFrom = "";
		state.priceTo = "";
		state.brandId = "";
		state.goodsList = [[], []];
		getGoodsPageList();
	}

	/** 点击遮罩 */
	const handleCloseMask = () => {
		state.selectIndex = -1;
	}

	// 组合商品数据传入组件
	const hanldeCombinationGoodsData = (item : GoodsType) => {
		return {
			id: item.id,
			image: item.image,
			name: item.name,
			brief: item.brief,
			price: item.price,
			mktprice: item.mktprice,
			isRecommend: item.isRecommend,
			isHot: item.isHot,
		}
	}

	const hanldeClickGoods = (item : GoodsType) => {
		uni.navigateTo({
			url: `/pages/goods/detail?id=${item.id}`
		})
	}

	const hanlderBack = () => {
		uni.navigateBack({
			delta: 1
		});
	}
</script>
<style lang="scss" scoped>
	@import './category.scss';
</style>